package com.tgy.leetcode;

import java.util.Arrays;
import java.util.TreeSet;

/**
 * https://leetcode-cn.com/problems/max-sum-of-rectangle-no-larger-than-k/
 */
public class _363_矩形区域不超过K的最大数值和 {

    public static int maxSumSubmatrix(int[][] matrix, int k) {

        int row = matrix.length;
        int col = matrix[0].length;

        int res = Integer.MIN_VALUE;
        for (int i = 0; i < row; i++) {

            int[] colSum = new int[col];
            for (int j = i; j < row; j++) {

                for (int l = 0; l < col; l++) {

                    colSum[l] += matrix[j][l];
                }
                TreeSet<Integer> treeSet = new TreeSet<>();
                // 加入0，代表没有值
                treeSet.add(0);
                int sum = 0;
                for (int cs : colSum) {

                    sum += cs;
                    Integer ceiling = treeSet.ceiling(sum - k);
                    if (ceiling != null) {

                        res = Math.max(res,sum - ceiling);
                    }
                    treeSet.add(sum);
                }
            }
        }

        return res;
    }

    public static void main(String[] args) {

//        int[][] martrix = {{1,0,1},{0,-2,3}};
        int[][] martrix = {{2,2,-1}};
        System.out.println(maxSumSubmatrix(martrix, 3));
    }
}
